#include "remote.h"
WiFiClient client;

unsigned long lastConnectAttempt = 0;
unsigned long lastDataTime = 0;           // 最后收到数据时间
const unsigned long CONNECT_INTERVAL = 5000;   // 重连间隔（ms）
const unsigned long HEARTBEAT_TIMEOUT = 10000; // 10秒没数据认为断开

bool shouldReconnect = true;  // 是否允许自动重连

String getRemoteIP() {
  IPAddress localIP = WiFi.localIP();
  IPAddress remoteIP(localIP[0], localIP[1], localIP[2], 146);
  return remoteIP.toString();  // 返回字符串形式
}
void checkConnection() {
  // 如果太久没收到数据，强制断开重连
  if (client.connected() && (millis() - lastDataTime) > HEARTBEAT_TIMEOUT) {
    Serial.println("data timeout, reconnecting...");
    client.stop();  // 关闭假连接
  }

  // 然后尝试重连
  if (!client.connected() && shouldReconnect && (millis() - lastConnectAttempt) > CONNECT_INTERVAL) {
    Serial.println("reconnecting");
    ConnectRemote(getRemoteIP());
    lastConnectAttempt = millis();
  }
}
bool ConnectRemote(String remote_ip) {
  // 尝试连接 TCP 服务器
  if (client.connect(remote_ip, remote_port)) {
    Serial.println("connected to server");
    client.print("noimg");
    lastDataTime = millis();
    return true;
  } else {
    Serial.println("failed to connect to server");
    return false;
  }
}
